package com.demo06.heap1;

/**
 * @Author: root
 * @Date: 2018/11/14 23:52
 */
public class BigHeapSort {
    public static void main(String[] args) {
        int[] arr = {10, 20, 7, 15, 0, 19, 1, 17, 30, 18, -1, 21};
        heapSort(arr, arr.length);
        for (int a : arr) {
            System.out.print(a + " ");
        }
        System.out.println();
    }

    private static void heapSort(int[] arr, int length) {
        for (int i = length / 2 - 1; i >= 0; i--) {
            adjustHeap(arr, i, length);
        }
        for (int i = length - 1; i >0; i--) {
            swap(arr, i, 0);
            adjustHeap(arr, 0, i);
        }
    }
    private static void adjustHeap(int[] arr, int i, int length) {
        int temp = arr[i];
        for (int k = 2 * i + 1; k < length; k = 2 * k + 1) {
            //找到左右孩子的最大值
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k++;
            }
            if (temp < arr[k]) {
                swap(arr, i, k);
                i = k;
            } else {
                break;
            }
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
